using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using KnowledgeQA.Core.Interfaces;
using KnowledgeQA.Models.DTOs;

namespace KnowledgeQA.API.Controllers
{
    /// <summary>
    /// 向量数据库控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class VectorController : ControllerBase
    {
        private readonly IVectorService _vectorService;
        private readonly ILogger<VectorController> _logger;

        public VectorController(IVectorService vectorService, ILogger<VectorController> logger)
        {
            _vectorService = vectorService;
            _logger = logger;
        }

        /// <summary>
        /// 获取向量数据库统计信息
        /// </summary>
        /// <returns>统计信息</returns>
        [HttpGet("stats")]
        public async Task<ActionResult<VectorDbStats>> GetStats()
        {
            try
            {
                var stats = await _vectorService.GetStatsAsync();
                return Ok(BaseResponse<VectorDbStats>.SuccessResult(stats));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取向量数据库统计信息失败");
                return StatusCode(500, BaseResponse<VectorDbStats>.ErrorResult("获取向量数据库统计信息失败"));
            }
        }

        /// <summary>
        /// 检查向量服务状态
        /// </summary>
        /// <returns>服务状态</returns>
        [HttpGet("status")]
        public async Task<ActionResult<object>> GetStatus()
        {
            try
            {
                var isAvailable = await _vectorService.IsAvailableAsync();
                var stats = await _vectorService.GetStatsAsync();
                
                var status = new
                {
                    IsAvailable = isAvailable,
                    VectorDbType = _vectorService.VectorDbType,
                    TotalVectors = stats.TotalVectors,
                    VectorDimension = stats.VectorDimension,
                    IndexSize = stats.IndexSize,
                    LastUpdated = stats.LastUpdated
                };

                return Ok(BaseResponse<object>.SuccessResult(status));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查向量服务状态失败");
                return StatusCode(500, BaseResponse<object>.ErrorResult("检查向量服务状态失败"));
            }
        }

        /// <summary>
        /// 获取向量信息
        /// </summary>
        /// <param name="vectorId">向量ID</param>
        /// <returns>向量信息</returns>
        [HttpGet("{vectorId}")]
        public async Task<ActionResult<VectorData>> GetVector(string vectorId)
        {
            try
            {
                var vector = await _vectorService.GetVectorAsync(vectorId);
                if (vector == null)
                {
                    return NotFound(BaseResponse<VectorData>.ErrorResult("向量不存在"));
                }

                return Ok(BaseResponse<VectorData>.SuccessResult(vector));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取向量信息失败，向量ID: {VectorId}", vectorId);
                return StatusCode(500, BaseResponse<VectorData>.ErrorResult("获取向量信息失败"));
            }
        }

        /// <summary>
        /// 测试向量搜索
        /// </summary>
        /// <param name="request">搜索请求</param>
        /// <returns>搜索结果</returns>
        [HttpPost("search")]
        public async Task<ActionResult<List<VectorSearchResult>>> Search([FromBody] VectorSearchRequest request)
        {
            try
            {
                if (request.QueryVector == null || request.QueryVector.Length == 0)
                {
                    return BadRequest(BaseResponse<List<VectorSearchResult>>.ErrorResult("查询向量不能为空"));
                }

                var results = await _vectorService.SearchAsync(
                    request.QueryVector,
                    request.TopK,
                    request.MinScore,
                    request.Filter
                );

                return Ok(BaseResponse<List<VectorSearchResult>>.SuccessResult(results));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "向量搜索失败");
                return StatusCode(500, BaseResponse<List<VectorSearchResult>>.ErrorResult("向量搜索失败"));
            }
        }

        /// <summary>
        /// 删除向量
        /// </summary>
        /// <param name="vectorId">向量ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{vectorId}")]
        public async Task<ActionResult<bool>> DeleteVector(string vectorId)
        {
            try
            {
                var success = await _vectorService.DeleteVectorAsync(vectorId);
                if (!success)
                {
                    return NotFound(BaseResponse<bool>.ErrorResult("向量不存在"));
                }

                return Ok(BaseResponse<bool>.SuccessResult(true));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除向量失败，向量ID: {VectorId}", vectorId);
                return StatusCode(500, BaseResponse<bool>.ErrorResult("删除向量失败"));
            }
        }

        /// <summary>
        /// 清空向量数据库
        /// </summary>
        /// <returns>清空结果</returns>
        [HttpDelete("clear")]
        public async Task<ActionResult<bool>> ClearAll()
        {
            try
            {
                var stats = await _vectorService.GetStatsAsync();
                var vectorIds = new List<string>();
                
                // 注意：这里需要实现获取所有向量ID的方法
                // 由于内存向量服务的限制，这里只是示例
                _logger.LogWarning("清空向量数据库功能需要实现获取所有向量ID的方法");
                
                var success = await _vectorService.DeleteVectorsAsync(vectorIds);
                return Ok(BaseResponse<bool>.SuccessResult(success));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清空向量数据库失败");
                return StatusCode(500, BaseResponse<bool>.ErrorResult("清空向量数据库失败"));
            }
        }
    }

    /// <summary>
    /// 向量搜索请求
    /// </summary>
    public class VectorSearchRequest
    {
        /// <summary>
        /// 查询向量
        /// </summary>
        public float[] QueryVector { get; set; } = Array.Empty<float>();

        /// <summary>
        /// 返回结果数量
        /// </summary>
        public int TopK { get; set; } = 5;

        /// <summary>
        /// 最小相似度分数
        /// </summary>
        public double MinScore { get; set; } = 0.7;

        /// <summary>
        /// 过滤条件
        /// </summary>
        public Dictionary<string, object>? Filter { get; set; }
    }
} 